<template>
  <div>
    <a-dropdown :trigger="['click']" v-model="show">
      <div slot="overlay">
        <a-spin :spinning="loading">
          <a-tabs
            class="dropdown-tabs"
            :tabBarStyle="{ textAlign: 'center' }"
            :style="{ width: '297px' }"
          >
            <a-tab-pane tab="通知" key="1">
              <a-list class="tab-pane">
                <a-list-item
                  style="cursor: pointer"
                  @click="noticeDetail(item)"
                  v-for="(item, index) in data"
                  :key="index"
                >
                  <a-list-item-meta
                    :title="item.message"
                    :description="item.createTimeFormat"
                  >
                    <a-avatar
                      style="background-color: #f5222d"
                      slot="avatar"
                      icon="mail"
                    />
                  </a-list-item-meta>
                </a-list-item>
              </a-list>
              <a-divider style="margin: 0" />
              <a-row type="flex">
                <a-col :span="12" @click="messageReadAll">
                  <div class="cell-content">清空通知</div></a-col
                >
                <a-col :span="12" @click="messageLogAll">
                  <div class="cell-content">查看更多</div></a-col
                >
              </a-row>
            </a-tab-pane>
            <!-- <a-tab-pane tab="消息" key="2">
            <a-list class="tab-pane"></a-list>
          </a-tab-pane>
          <a-tab-pane tab="待办" key="3">
            <a-list class="tab-pane"></a-list>
          </a-tab-pane> -->
          </a-tabs>
        </a-spin>
      </div>
      <span class="header-notice">
        <a-badge class="notice-badge" :count="total">
          <a-icon :class="['header-notice-icon']" type="bell" />
        </a-badge>
      </span>
    </a-dropdown>
    <workflow-view
      ref="workflowView"
      v-if="workflowDo.visible"
      :visible.sync="workflowDo.visible"
      :title="workflowDo.title"
      :isWorkflow="true"
      :workflowData="workflowDo.data"
      @ok="workDoOk"
    ></workflow-view>
  </div>
</template>

<script>
import workflowView from "@/pages/system/agile/run/edit";
import { query, findById, read } from "@/services/system/messagelog/header";
import { mapGetters } from "vuex";
import * as signalR from "@microsoft/signalr";
export default {
  name: "HeaderNotice",
  components: {
    workflowView,
  },
  data() {
    return {
      loading: false,
      show: false,
      connection: null,
      total: 0,
      data: [],

      //编辑组件
      workflowDo: {
        visible: false,
        title: null,
        isWorkflow: false,
        data: {
          processId: null, //流程实例Id
          processInstanceId: null,
          activityId: null,
          taskId: null,
          doType: 1, //处理类型1审核，2知会，3加签，4阅示，5流程监控，6阅示审批处理,有通过和拒绝按钮
        },
        update: {
          relationId: null, //业务表主键Id
        },
      },
    };
  },
  computed: {
    ...mapGetters("account", ["user"]),
  },
  created() {
    this.initSignalr();
    this.initNotice();
  },
  methods: {
    initNotice() {
      let that = this;
      query({
        current: 1,
        size: 999,
      }).then(function (result) {
        that.total = result.count;
        that.data = result.data;
      });
    },

    /**
     * 初始化连接器
     */
    initSignalr() {
      let that = this;
      var BASE_URL =
        process.env.NODE_ENV === "production"
          ? process.env.VUE_APP_API_BASE_URL
          : "http://localhost:53604";
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl(BASE_URL + "/eiphub", {})
        .configureLogging(signalR.LogLevel.Error)
        .build();
      this.connection.on("SendMessageAll", (user, message) => {
        console.log(user, message);
      });
      this.connection.on("SendWebSiteMessage", (message) => {
        const key = `open${Date.now()}`;
        if (message) {
          var data = JSON.parse(message);
          that.$notification["info"]({
            message: data.Title,
            description: data.Message,
            placement: "bottomRight",
            btn: (h) => {
              return h(
                "a-button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      that.noticeDetail({
                        messageLogId: data.MessageLogId,
                      });
                    },
                  },
                },
                "立即查看"
              );
            },
            key,
            onClose: close,
          });

          that.initNotice();
        }
      });
      this.connection.start().then(() => {
        that.connection.invoke("SendUserOnline", that.user);
      });
    },

    /**
     *
     */
    messageLogAll() {
      this.$openPage("/pages/system/messagelog/list", "所有消息");
    },

    /**
     * 阅读所有
     */
    messageReadAll() {
      let that = this;
      this.show = false;
      if (this.data.length > 0) {
        that.$loading.show({ text: "处理中..." });
        var ids = this.data.map((f) => f.messageLogId).join(",");
        read({
          messageLogIds: ids,
        }).then((result) => {
          that.initNotice();
          that.$loading.hide();
        });
      }
    },

    /**
     *
     * @param {*} messageLog
     */
    noticeDetail(messageLog) {
      let that = this;
      this.show = false;
      that.$loading.show({ text: "处理中..." });
      read({
        messageLogIds: messageLog.messageLogId,
      }).then((result) => {
        that.initNotice();
      });

      //读取消息明细
      findById(messageLog.messageLogId).then((result) => {
        var row = result.data;

        if (row.openUrl == "workflowView") {
          that.workflowDo.title = "处理流程-" + row.title;
          var workflowData = JSON.parse(row.customerData);
          that.workflowDo.data = {
            processInstanceId: workflowData.ProcessInstanceId,
            activityId: workflowData.ActivityId,
            taskId: workflowData.TaskId,
            type: that.eipWorkflowDoType["阅示审批"],
          };
          that.workflowDo.visible = true;
        }

        if (row.openUrl == "workflwCuiBan") {
          that.workflowDo.title = "处理流程-" + row.title;
          var workflowData = JSON.parse(row.customerData);
          that.workflowDo.data = {
            processInstanceId: workflowData.ProcessInstanceId,
            activityId: workflowData.ActivityId,
            taskId: workflowData.TaskId,
            type: that.eipWorkflowDoType["审核"],
          };
          that.workflowDo.visible = true;
        }
      });
      that.$loading.hide();
    },

    workDoOk() {},
  },
};
</script>

<style lang="less">
.header-notice {
  display: inline-block;
  transition: all 0.3s;
  span {
    vertical-align: initial;
  }
  .ant-badge-count {
    top: 2px !important;
  }
  .notice-badge {
    color: inherit;
    .header-notice-icon {
      font-size: 16px;
      padding: 4px;
    }
  }
}
.dropdown-tabs {
  background-color: @base-bg-color;
  box-shadow: 0 2px 8px @shadow-color;
  border-radius: 4px;
  .tab-pane {
    padding: 0 24px 12px;
    min-height: 250px;
  }
}
.cell-content {
  line-height: 46px;
  text-align: center;
  transition: background-color 0.3s;
  cursor: pointer;
  color: inherit;
}
.cell-content:hover {
  background: hsla(0, 0%, 60%, 0.05);
}
</style>
